﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Runtime.Serialization.Formatters.Binary;

namespace ZWZ.Web.Codes
{
    public static class SerializeHelper
    {
        ///   <summary> 
        ///   把对象序列化并返回相应的字节 
        ///   </summary> 
        ///   <param   name= "pObj "> 需要序列化的对象 </param> 
        ///   <returns> byte[] </returns> 
        public static byte[] SerializeObject(object pObj)
        {
            if (pObj == null)
                return null;
            System.IO.MemoryStream _memory = new System.IO.MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(_memory, pObj);
            _memory.Position = 0;
            byte[] read = new byte[_memory.Length];
            _memory.Read(read, 0, read.Length);
            _memory.Close();
            return read;
        }

        /// <summary>
        /// 把对象序列化并返回相应的字节 
        /// </summary>
        /// <param name="pOjb"></param>
        /// <returns></returns>
        public static string SerializeObjectToString(object pOjb)
        {
            Byte[] bytes = SerializeObject(pOjb);
            return System.Convert.ToBase64String(bytes);
        }

        ///   <summary> 
        ///   把字节反序列化成相应的对象 
        ///   </summary> 
        ///   <param   name= "pBytes "> 字节流 </param> 
        ///   <returns> object </returns> 
        public static object DeserializeObject(byte[] pBytes)
        {
            object _newOjb = null;
            if (pBytes == null)
                return _newOjb;
            System.IO.MemoryStream _memory = new System.IO.MemoryStream(pBytes);
            _memory.Position = 0;
            BinaryFormatter formatter = new BinaryFormatter();
            _newOjb = formatter.Deserialize(_memory);
            _memory.Close();
            return _newOjb;
        }

        /// <summary>
        /// 把字节反序列化成相应的对象 
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static object DeserializeObjectByString(string text)
        {
            Byte[] bytes = System.Convert.FromBase64String(text);
            return DeserializeObject(bytes);
        }
    }
}